package cn.sunlight.mm.controller;

import cn.sunlight.framework.annotation.HmComponent;
import cn.sunlight.framework.annotation.HmRequestMapping;
import cn.sunlight.framework.annotation.HmSetter;
import cn.sunlight.mm.base.BaseController;
import cn.sunlight.mm.common.GlobalConst;
import cn.sunlight.mm.entity.Result;
import cn.sunlight.mm.pojo.User;
import cn.sunlight.mm.service.UserService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author sunlight
 * @description: 用户控制器（子控制器）
 * @date 2021/5/18
 * @Version v1.0
 */
@Slf4j
@HmComponent
public class UserController extends BaseController {

    @HmSetter("userService")
    UserService userService;

    /**
     * 用户登录
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/user/login")
    public void login (HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info("UserController save...");
        //接收表单数据并封装到POJO对象
        User loginForm= JSON.parseObject(request.getInputStream(), User.class);
        log.debug("user:{}",loginForm);
        //调用业务
        User user=userService.findUserByUsermame(loginForm.getUsername());
        //判断用户是否为空
        if(user==null){
            //响应JSON
            printResult(response,new Result(false,"登录失败，用户不存在"));
            return;
        }
        //判断用户名密码是否一致
        if(user.getPassword().equals(loginForm.getPassword())){
            // 登录成功，创建session，并把对象存入Session
            // true,没有session,创建Session
            request.getSession(true).setAttribute(GlobalConst.SESSION_KEY_USER,user);
            //登录成功，获取用户权限列表（通过userService）
            List<String> authList=userService.getAuthList(user.getId());
            user.setAuthorityList(authList);

            printResult(response,new Result(true,"登录成功"));
        }else{
            printResult(response,new Result(false,"登录失败，密码错误"));
        }
    }

    /**
     * 退出系统
     * @param request
     * @param response
     * @throws Exception
     */
    @HmRequestMapping("/user/logout")
    public void logout (HttpServletRequest request, HttpServletResponse response) throws Exception {
        //销毁会话，如果没有会话不需要创建会话
        HttpSession session = request.getSession(false);
        if (session!=null){
            //销毁session
            log.debug("销毁session。。。。。。");
            session.invalidate();
        }else {
            log.debug("session已失效");
        }
        printResult(response,new Result(true,"登录成功"));
    }

}
